//登录组件
import React, { Component } from 'react'
import {
    NavBar,
    WingBlank,
    List,
    InputItem,
    WhiteSpace,
    Button,
    Toast
} from 'antd-mobile'
import Logo from '../../components/logo/logo'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'
import { login } from '../../redux/actions'

const ListItem = List.Item

class Login extends Component {
    state = {
        username: '',
        password: '',
    }

    login = () => {
        this.props.login(this.state)
    }
    //处理输入数据的改变，更新对应的状态
    handleChange = (name, val) => {
        //更新状态
        this.setState({
            [name]: val //属性名不是name而是name变量的值
        })
    }

    toRegister = () => {
        this.props.history.replace('/register')
    }

    render() {
        const { msg, redirecTo } = this.props.user
        //如果redirecTo有值，就需要重定向
        if (redirecTo) {
            return <Redirect to={redirecTo} />
        }
        if(msg){
            Toast.fail(msg)
        }

        return (
            <div>
                <NavBar>狗&nbsp;狗&nbsp;直&nbsp;聘</NavBar>
                <Logo />
                <WingBlank>
                    <List>
                        <WhiteSpace></WhiteSpace>
                        <InputItem placeholder='请输入用户名' onChange={val => { this.handleChange('username', val) }}>用户名:</InputItem>
                        <WhiteSpace></WhiteSpace>
                        <InputItem placeholder='请输入密码' type="password" onChange={val => { this.handleChange('password', val) }}>密&nbsp;&nbsp;&nbsp;码:</InputItem>
                        <WhiteSpace></WhiteSpace>
                        <Button type="primary" onClick={this.login}>登录</Button>
                        <WhiteSpace></WhiteSpace>
                        <WhiteSpace></WhiteSpace>
                        <Button type="warning" onClick={this.toRegister}>未有账户</Button>
                    </List>
                </WingBlank>
            </div>
        )
    }
}
export default connect(
    state => ({ user: state.user }),
    { login }
)(Login)